package com.djx.监听;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.junit.Test;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * 客户端与服务器的连接状态
 */
public class ZKConnectionWatcher implements Watcher {

    //    ZooKeeper zooKeeper = new MyZookepper01().zooKeeper;
    private final String myIP = "192.168.15.132:2181";
//    CountDownLatch countDownLatch = new CountDownLatch(1);

    /**
     * 连接四种状态
     *
     * @param watchedEvent
     */
    public void process(WatchedEvent watchedEvent) {
        try {

            if (watchedEvent.getType() == Event.EventType.None) {
                if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
                    System.out.println("连接创建成功！");
//                    countDownLatch.countDown();
                } else if (watchedEvent.getState() == Event.KeeperState.Disconnected) {
                    System.out.println("断开连接！");
                } else if (watchedEvent.getState() == Event.KeeperState.Expired) {
                    System.out.println("回话超时！");
                    //捕获到会话超时 就要继续连接 也就是连接对象的创建重新连接
//                    zK();
                } else if (watchedEvent.getState() == Event.KeeperState.AuthFailed) {
                    System.out.println("认证失败！");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void zK() throws IOException, InterruptedException, KeeperException {
        ZooKeeper zooKeeper = new ZooKeeper(myIP, 5000, new ZKConnectionWatcher());
//        countDownLatch.await();
        //添加授权用户
        zooKeeper.addAuthInfo("digest1", "djx:1234566".getBytes()); //错误用户名密码认证失败
        System.out.println("已认证");
        byte[] node01s = zooKeeper.getData("/node01", false, null);
        System.out.println("数据为 :  "+new String(node01s));

        System.out.println("sessionID为： " + zooKeeper.getSessionId());
        Thread.sleep(5000);
        zooKeeper.close();
        System.out.println("结束!");


    }

    @Test
    public void zk02() {
    }


}
